//
//  NativeScanChannel.m
//  kq_flutter_widgets
//
//  Created by wtb on 2023/4/7.
//

#import "NativeScanChannel.h"
#import "KqTool.h"

@implementation NativeScanChannel

+(void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar{
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"flutter.keqiang.com/scan" binaryMessenger:[registrar messenger]];
    NativeScanChannel *scan = [[NativeScanChannel alloc] init];
    [registrar addMethodCallDelegate:scan channel:channel];
}

-(void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if ([@"startScan" isEqualToString:call.method]){
        NSString *title = call.arguments[@"title"];
        bool useAlbum = [call.arguments[@"useAlbum"] boolValue];
        
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        if(title && ![title isEqual:[NSNull null]]){
            [dic setValue:title forKey:@"title"];
        }
        [dic setValue:[NSNumber numberWithBool:!useAlbum] forKey:@"notSupportAlbum"];
        void (^scanResultBlock)(NSString *scanResult, NSString *scanType) = ^(NSString *scanResult, NSString *scanType){
            if (scanResult) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic setValue:@1 forKey:@"code"];
                [dic setValue:scanResult forKey:@"data"];
                [dic setValue:@"" forKey:@"msg"];
                result(dic);
            }else{
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic setValue:@0 forKey:@"code"];
                [dic setValue:@"扫码失败" forKey:@"msg"];
                result(dic);
            };
        };
        [dic setValue:scanResultBlock forKey:@"result"];
        // code 为2，flutter不弹出消息
        void (^scanCancelBlock)(void) = ^(){
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:@2 forKey:@"code"];
            [dic setValue:@"取消扫码" forKey:@"msg"];
            result(dic);
        };
        [dic setValue:scanCancelBlock forKey:@"backBlock"];
        [KqTool kqPushWithUrl:@"GFScanViewController" property:dic];
    }
}
@end
